package com.david.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

/**
 * @program: Secondskill-Demo
 * @description: MD5工具类
 * @author: David
 * @version:
 * @create: 2022-04-11 17:37
 **/
@Component
public class MD5Util {

    public static String md5(String src){

        return DigestUtils.md5Hex(src);
    }

    /**
     * 自定义盐 salt = "1a2b3c4d";
     */
    private static final String salt = "1a2b3c4d";

    /**
     * 第一次加密
     * @param inputPassword 输入的密码
     * @return
     */
    public static String inputPassFormPassword(String inputPassword){
        String str = "" + salt.charAt(0)+salt.charAt(2)+inputPassword+salt.charAt(5)+salt.charAt(4);
        return md5(str);
    }

    /**
     *
     * @param formPasswordToDBPass 第二次加密,向数据库保存的时候进行加密
     * @param salt 这个盐会存到数据库
     * @return
     */
    public static String formPasswordToDBPassword(String formPasswordToDBPass,String salt){
        String str = "" + salt.charAt(0)+salt.charAt(2)+formPasswordToDBPass+salt.charAt(5)+salt.charAt(4);
        return md5(str);
    }

    /**
     * 这是最终需要的DBPassword
     * @param inputPassword
     * @param salt
     * @return
     */
    public static String inputPasswordToDBPass(String inputPassword,String salt){
        String formPassword = inputPassFormPassword(inputPassword);
        String DBPassword = formPasswordToDBPassword(formPassword,salt);
        return DBPassword;
    }

    /**
     * 测试MD5
     * @param args
     */
    public static void main(String[] args) {
        /**
         * 第一层密码  d3b1294a61a07da9b49b6e22b2cbd7f9
         * 第二层密码  b7797cce01b4b131b433b6acf4add449
         * 第三层密码  b7797cce01b4b131b433b6acf4add449
         * 最终调用   inputPasswordToDBPass
         */
        System.out.println(inputPassFormPassword("123456"));
        System.out.println(formPasswordToDBPassword("d3b1294a61a07da9b49b6e22b2cbd7f9","1a2b3c4d"));
        System.out.println(inputPasswordToDBPass("123456","1a2b3c4d"));
    }
}
